const { Add, Update, Exec, QueryOne, QueryById } = require('../db/dbhelper');
var { init, format } = require('../models/authrealname');
var { peopleQueryOne, peopleUpdate } = require('./people');
var authface_api = require('./ossfile').authface_api;
var { formatDate, formatDateTime, getStar, getAge } = require('../libs/common');
var _ = require('underscore');
var { sendMsg } = require('./wechat');
const logger = require('../libs/log').logger;
let { IdCardVerification }= require('../libs/tencent_cloud');
var moment = require('moment');

//列表
const authrealnameList = async function (doc) {
  try {
    let { ispass, name, pagenum, pagesize } = doc;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    let sql = 'SELECT * FROM hzz_authrealnames WHERE 1=1 ';
    let sql_filter = '';
    if (ispass || ispass == 0) {
      sql_filter += ' AND ispass = ' + ispass;
    }
    if (name) {
      sql_filter += ` AND (nickname LIKE '%${name}%' OR NAME LIKE '%${name}%') `;
    }
    sql += sql_filter;
    sql += ' ORDER BY updatetime DESC,id ASC ';

    sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `;
    let list = await Exec(sql);

    let pcodes = _.compact(_.pluck(list, 'pcode'));
    let plist = [];
    if (pcodes && pcodes.length) {
      plist = await Exec(`select code,invitcode from hzz_peoples where code in(${pcodes.join(',')})`)
    }
    let tcodes = _.compact(_.pluck(plist, 'invitcode'));
    let tlist = [];
    if (tcodes && tcodes.length) {
      tlist = await Exec(`select name,name_father,code,is_father from hzz_peoples where code in(${tcodes.join(',')})`)
    }
    plist = _.map(plist,function(x){
      let tt= _.find(tlist,function(t){
        return t.code == x.invitcode;
      })
      if(tt){
        x.invitername = tt.is_father ? tt.name_father: tt.name;
      }else{
        x.invitername = '';
      }
      return x;
    })

    list = _.map(list, function (item) {
      item.idcard = item.idcard? item.idcard.substr(0,14)+'****' : '';
      // item = _.omit(item,'img','img_back');
      item.createtime = formatDateTime(item.createtime);
      item.updatetime = formatDateTime(item.updatetime);
      item.audittime = formatDateTime(item.audittime);
      let tiv = _.find(plist,function(t){
        return t.code == item.pcode;
      })
      item.invitername = tiv ? tiv.invitername :'';
      return item;
    });

    let total_sql = 'SELECT count(1) as total FROM hzz_authrealnames  WHERE 1=1 ' + sql_filter;
    let total_data = await Exec(total_sql);
    let total = total_data && total_data.length ? total_data[0].total : 0;

    let pagecount = Math.ceil(total / pagesize);
    return {
      code: 0,
      data: {
        list,
        total,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}
// 提交
const authrealnameSave = async function (doc) {
  try {
    logger.info('---------------authrealnameSave-------------doc:', doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: '请重新登录'
      }
    }
    if (!doc.authtype) {
      return {
        code: 1,
        msg: '请选择认证方式'
      }
    }
    if (!doc.name) {
      return {
        code: 1,
        msg: '请填写姓名'
      }
    }
    if (!doc.idcard) {
      return {
        code: 1,
        msg: '请填写证件号码'
      }
    }
    // if (!doc.img) {
    //   return {
    //     code: 1,
    //     msg: '请上传证件照片'
    //   }
    // }

    // 获取用户nickname、name
    let people = await QueryOne('hzz_peoples', { code: doc.pcode }, 'id,nickname,name,is_father,reliability');
    if (people) {
      doc.nickname = people.nickname;
      doc.is_father = people.is_father;
    }
    doc.audittime = new Date();
    let pl = await QueryOne('hzz_authrealnames', { pcode: doc.pcode }, null);
    if (pl) {
      doc.id = pl.id;
      let his = pl.audithistory ? JSON.parse(pl.audithistory) : [];
      his.push({
        ispass: pl.ispass,
        commit: pl.commit,
        audittime: pl.audittime
      });
      doc.audithistory = JSON.stringify(his);
      await Update('hzz_authrealnames', format(doc));
    } else {
      pl = await Add('hzz_authrealnames', init(doc));
    }
    // 更新用户实名认证状态为：认证中
    await peopleUpdate({ pcode: doc.pcode, cross_realname_auth: 2 });
    // 提交实名认证审核-异步后台自动执行
    let objectname = doc.img.split('/')[doc.img.split('/').length - 1];
    return await authface_audit_auto(people.id, pl.id, { pcode: doc.pcode, idcard: doc.idcard, name: doc.name, objectname: objectname, is_father: doc.is_father,reliability: people.reliability });
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '提交异常'
    }
  }
}
// 实名认证
const authface_audit_auto = async function (peopleId, id, parmas) {
  // let auth_res = await authface_api(parmas);
  let auth_resData = await IdCardVerification({IdCard: parmas.idcard, Name: parmas.name});
 
  let auth_res ={
    code: auth_resData? Number(auth_resData.Result): 1,
    msg: auth_resData? auth_resData.Description: '认证失败，请联系客服'
  };
  logger.info('-----authface_audit_auto-------,auth_res',auth_res)
  if (auth_res.code) {
    // 认证失败
    // 更新认证状态-失败
    Update('hzz_authrealnames', { id: id, ispass: 0, commit: auth_res.msg || '身份认证失败' });
    // 更新员工身份认证状态为：认证失败
    peopleUpdate({ id: peopleId, pcode: parmas.pcode, cross_realname_auth: 9 });
    // 发送认证失败消息
    let send_data = {
      "first": {
        "value": "身份认证",
        "color": "#173177"
      },
      "keyword1": {
        "value": auth_res.msg || "您提交的身份认证资料，平台审核未通过，请重新提交或联系客服咨询！",
        "color": "#173177"
      },
      "keyword2": {
        "value": "认证失败！",
        "color": "#e8320e"
      },
      "remark": {
        "value": "请检查提交信息是否完整。",
        "color": "#173177"
      }
    };
    let send_data_red = {
      "thing2": {
        "value": "身份认证"
      },
      "phrase1": {
        "value": "认证失败"
      },
      "thing4": {
        "value": auth_res.msg || "您提交的身份认证资料，平台审核未通过，请重新提交或联系客服咨询！"
      },
      "time3": {
        "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
      }
    };
    sendMsg('realauth_tmpid', send_data, parmas.pcode,'myInfo',send_data_red);
  } else {
    // 认证成功
    // 更新认证状态-成功
    Update('hzz_authrealnames', { id: id, ispass: 1, commit: auth_res.msg || '身份认证成功' });
    // 更新用户是否通过实名认证状态为：已通过
    let upOBJ = {
      id: peopleId, cross_realname_auth: 1, reliability: parmas.reliability+30
    };
    if(parmas.is_father){
      upOBJ.idcard_father = parmas.idcard;
      upOBJ.name_father = parmas.name;
    }else{
      upOBJ.idcard = parmas.idcard;
      upOBJ.name = parmas.name;
      let bir = parmas.idcard.substr(6,8);
      let reg=/^(\d{4})(\d{2})(\d{2})$/;
      bir = bir.replace(reg,'$1-$2-$3');
      upOBJ.birthday = new Date(bir);
      upOBJ.age = getAge(bir);
      upOBJ.star = getStar(bir);
    }
    
    logger.info('-----authface_audit_auto-------,peopleUpdate,upOBJ',upOBJ)
    let peopleData = await QueryById('hzz_peoples',peopleId);
    upOBJ.grade = peopleData.grade+1;
    peopleUpdate(upOBJ);
    // 发送认证成功消息
    let send_data = {
      "first": {
        "value": "身份认证",
        "color": "#173177"
      },
      "keyword1": {
        "value": "您提交的身份认证资料，平台审核已通过！",
        "color": "#173177"
      },
      "keyword2": {
        "value": "认证成功！",
        "color": "#74BB44"
      },
      "remark": {
        "value": "您可以进行后续操作。",
        "color": "#173177"
      }
    };
    let send_data_red = {
      "thing2": {
        "value": "身份认证"
      },
      "phrase1": {
        "value": "认证成功"
      },
      "thing4": {
        "value": "您提交的身份认证资料，平台审核已通过"
      },
      "time3": {
        "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
      }
    };
    sendMsg('realauth_tmpid', send_data, parmas.pcode,'myInfo',send_data_red);
  }
  return auth_res;
}

module.exports = {
  authrealnameList,
  authrealnameSave
}